from crispy_forms.layout import Submit
from django import forms
from django.forms import ModelForm, Select, DateTimeInput
from .models import Products, Tasks
from datetime import datetime
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Fieldset, Submit, Row, Column, Field
from django.urls import reverse


class ChartSellerForm(forms.Form):
    category = forms.ChoiceField(label='类别')
    date = forms.ChoiceField(label="日期")
    low_sale = forms.IntegerField(min_value=100, label="最低销量")
    low_reviews = forms.IntegerField(min_value=300, label="最低评论数")

    def __init__(self, *args, **kwargs):
        super(ChartSellerForm, self).__init__(*args, **kwargs)
        self.fields['low_sale'].widget.attrs.update({'placeholder': '最低销量'})
        self.fields['low_reviews'].widget.attrs.update(
            {'placeholder': '最低评论数'})
        # retrieve category from short_name field
        products_qs = Products.objects.all()
        ds = products_qs.order_by("short_name").values("short_name").distinct()
        self.category_list = [(str(i), x['short_name'])
                              for i, x in enumerate(ds)]
        self.fields['category'].choices = self.category_list
        self.fields['category'].default = "1"
        self.fields['category'].widget.attrs.update(
            {'class': 'form-control', 'placeholder': '类别'})
        # retrieve date from create_time field
        res = products_qs.filter(
            bought_last_month__gte=100).order_by("-create_time").values_list('create_time')
        date_set = set([r[0].strftime("%Y-%m-%d") for r in res])
        date_set = sorted(list(date_set), reverse=True)
        self.date_list = [(str(i), d) for i, d in enumerate(date_set)]
        self.fields['date'].choices = self.date_list
        print("ChartSellerForm init")

        self.helper = FormHelper()
        self.helper.form_id = 'id-exampleForm'
        self.helper.form_method = 'post'
        self.helper.form_action = "/v1/chart/seller/"
        self.helper.add_input(Submit('submit', '提交'))
        self.helper.layout = Layout(
            Row(
                Column('category', css_class='form-group col-md-6 mb-0'),
                Column('date', css_class='form-group col-md-6 mb-0'),
                css_class='form-row'
            ),
            Row(
                Column('low_sale', css_class='form-group col-md-6 my-0'),
                Column('low_reviews', css_class='form-group col-md-6 my-0'),
                css_class='form-row'
            )
        )


class TasksCreateForm(ModelForm):
    class Meta:
        model = Tasks
        fields = ['name', 'kw', 'type', 'start_time', 'end_time',
                  'cron_day', 'cron_weekday', 'cron_hour', 'cron_minute', 'status']
        labels = {
            'cron_day': '每月天数',
            'cron_weekday': '每周天数',
            'cron_hour': '几点',
            'cron_minute': '几分',
        }
        help_texts = {
            'kw': '搜索词为英文，必须为商品名称中的关键词，如charger',
            'cron_day': 'cron字符串,指定每个月的天数,如 1-5, 1,5,10...',
            'cron_weekday': 'cron字符串,周几，如 0-6, 0,6...',
            'cron_hour': 'cron字符串,小时，如 0-23, 0,6...',
            'cron_minute': 'cron字符串,分钟，如 0-59, 0,6...',
        }
        widgets = {
            'type': Select(attrs={'class': 'my-select'}),
            'start_time': DateTimeInput(
                attrs={
                    'type': 'datetime-local',
                    'class': 'form-control'
                }
            ),
            'end_time': DateTimeInput(
                attrs={
                    'type': 'datetime-local',
                    'class': 'form-control'
                }
            ),
        }
        error_messages = {
            'name': {
                'max_length': "Task name is too long.",
            },
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['start_time'].initial = datetime.now().strftime(
            "%Y-%m-%dT%H:%M")
        self.helper = FormHelper()
        self.helper.form_method = "post"
        self.helper.form_action = "/v1/tasks/create/"
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-lg-2'
        self.helper.field_class = 'col-lg-7'
        self.helper.add_input(Submit('submit', '提交'))


class TasksUpdateForm(ModelForm):
    class Meta:
        model = Tasks
        fields = ['name', 'kw', 'type', 'start_time', 'end_time',
                  'cron_day', 'cron_weekday', 'cron_hour', 'cron_minute', 'status']

        labels = {
            'cron_day': '每月天数',
            'cron_weekday': '每周天数',
            'cron_hour': '几点',
            'cron_minute': '几分',
        }
        help_texts = {
            'kw': '搜索词为英文，必须为商品名称中的关键词，如charger',
            'cron_day': 'cron字符串,指定每个月的天数,如 1-5, 1,5,10...',
            'cron_weekday': 'cron字符串,周几，如 0-6, 0,6...',
            'cron_hour': 'cron字符串,小时，如 0-23, 0,6...',
            'cron_minute': 'cron字符串,分钟，如 0-59, 0,6...',
        }
        widgets = {
            'type': Select(attrs={'class': 'my-select'}),
        }
        error_messages = {
            'name': {
                'max_length': "Task name is too long.",
            },
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['start_time'].initial = datetime.now().strftime(
            "%Y-%m-%dT%H:%M")
        self.helper = FormHelper()
        self.helper.form_method = "post"
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-lg-2'
        self.helper.field_class = 'col-lg-7'
        self.helper.form_action = reverse(
            'datapanel:tasks_update', kwargs={'pk': self.instance.pk})
        self.helper.add_input(Submit('submit', '提交'))
